<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class ActivityController extends AdminController{
    
//    public function filters(){
//        return array(
//               'accessControl',
//        );
//    }

    
//    public function accessRules()
//    {
//        return array(
//            array('allow', // allow all users to perform 'index' and 'view' actions
//                'actions'=>array('index','view'),
//                'users'=>array('@'),
//                                'roles' => array('admin', 'editor', 'reader'),
//            ),
//            array('allow', // allow authenticated user to perform 'create' and 'update' actions
//                'actions'=>array('index','update'),
//                'users'=>array('@'),
//                                'roles' => array('admin', 'owner'),
//            ),
//            array('allow', // allow admin user to perform 'admin' and 'delete' actions
//                'actions'=>array('index','delete'),
//                'users'=>array('@'),
//                                'roles' => array('admin'),
//            ),
//            array('deny', // deny all users
//                'users'=>array('*'),
//            ),
//        );
//    }
    
    
    public function actionIndex()
    {
        // p_e(Yii::app()->user->Alumni_id); 
       
        $Activity = new Activity();
        $Activity->unsetAttributes();
        if(isset($_GET['Activity'])){
            $Activity->attributes=$_GET['Activity'];
         }
         
         //设置热点
        if(Yii::app()->request->isAjaxRequest){
           if(isset($_POST['id'])&&isset($_POST['is_hot'])){
                if($_POST['is_hot'] ==2){ 
                     $sql_a = "update xyh_activity set is_hot=2 where is_hot=1";
                    $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                     $sql_a = "update xyh_activity set is_hot=1 where id={$_POST['id']}";
                   $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                }
           }
       } 
         
          //添加分类
        if(Yii::app()->request->isAjaxRequest){
           if(isset($_POST['type_name'])){               
                $Type = new Type();
                $Type->name = $_POST['type_name'];
                $Type->sign = 11;
                $Type->save(false);
                $Type_id =Yii::app()->db->getLastInsertID();
                $Type->sort = $Type_id;
                $Type->save(false); 
           }
       }
            
        $this->render('index',array(
               'Activity'=>$Activity      
        ));
    }
    
   
    public function actionAdd(){
        
        $Activity = new Activity();  
        $ActivityLinkSignup = new ActivityLinkSignup();
        $ActivityLinkVoteA = new ActivityLinkVoteA();
        $ActivityLinkVoteQ = new ActivityLinkVoteQ();
        
        
       $Activity->unsetAttributes();
       $ActivityLinkSignup->unsetAttributes();
       $ActivityLinkVoteA->unsetAttributes();
       $ActivityLinkVoteQ->unsetAttributes();
       
       
       $Activity->is_hot =2;
        $ActivityLinkSignup->is_need_lottery =2;
        $ActivityLinkSignup->is_need_signup =2;
        $ActivityLinkSignup->is_need_checkin =2;

       if(isset($_GET['Activity'])){
            $Activity->attributes=$_GET['Activity'];
        }


        if((isset($_POST['ajax']) && $_POST['ajax']==='active-form'))
        {         
            echo CActiveForm::validate(array($Activity,$ActivityLinkSignup));  
            Yii::app()->end();
        }
        if((isset($_POST['ajax']) && $_POST['ajax']==='vote-form'))
        {        
            echo CActiveForm::validate(array($Activity,$ActivityLinkSignup));  
            Yii::app()->end();
        }
        
        // collect user input data
        if(isset($_POST['Activity']) && isset($_POST['Activity']))
        {	
               // 
           $data = $this->Data_Pro($_POST);
           p_e($data); 
           if($data['Activity']['is_hot'] ==1){ 
                    $sql_a = "update xyh_activity set is_hot=2 where is_hot=1";
                    $Db = Yii::app()->db->createCommand($sql_a)->execute(); 
                    if(!$Db){
                        return FALSE;
                    }
            }
           
           $Activity->ctime = time();
           $Activity->attributes = $data['Activity'];
           
           $transaction  =Yii::app()->db->beginTransaction();
            
           if($Activity->save())
            {
               $Activity_id =Yii::app()->db->getLastInsertID();
               $data['ActivityLinkVoteQ']['activity_id']=$Activity_id;
               
               if($data['Activity']['type_id'] ==102){
                    foreach ($data['ActivityLinkVoteQ']['q_content'] as $k=>$v)
                    {                   
                             $data['ActivityLinkVoteQ'][$k]['activity_id']= $Activity_id;
                             $data['ActivityLinkVoteQ'][$k]['q_content'] =$v;
                             $data['ActivityLinkVoteQ'][$k]['type_id'] = $data['ActivityLinkVoteQ']['type_id'];
                             $data['ActivityLinkVoteQ'][$k]['sort'] =($k);

                             $ActivityLinkVoteQ->attributes = $data['ActivityLinkVoteQ'][$k];
                              //p_e($ActivityLinkVoteQ->attributes);
                             if ($ActivityLinkVoteQ->save(false)){
                                 $ActivityLinkVoteQ = new ActivityLinkVoteQ();
                                 $vote_id = Yii::app()->db->getLastInsertID();
                                  foreach ($data['ActivityLinkVoteA']['a_content'][$k] as $kk=>$vv)
                                {                   
                                         $data['ActivityLinkVoteA'][$kk]['activity_id']= $Activity_id;
                                         $data['ActivityLinkVoteA'][$kk]['vote_q_id']= $vote_id;
                                         $data['ActivityLinkVoteA'][$kk]['a_content'] =$vv;
                                         
                                         $data['ActivityLinkVoteA'][$kk]['sort'] =($kk);

                                         $ActivityLinkVoteA->attributes = $data['ActivityLinkVoteA'][$kk];

                                          //p_e($ActivityLinkVoteA->attributes);

                                         if ($ActivityLinkVoteA->save(false)){
                                             $ActivityLinkVoteA = new $ActivityLinkVoteA();
                                         }
                                         else{
                                            
                                             $transaction->rollback();
                                              $ErrorMessage = BootExtend::GetErrorMassage($ActivityLinkVoteA);
                                              Yii::app()->jump->error('添加失败!'.'错误信息--('.$ErrorMessage.')');
                                              
                                             barek;
                                         }
                                 }
                                 
                                 
                             }
                             else{
                                 
                                 $transaction->rollback();
                                 $ErrorMessage = BootExtend::GetErrorMassage($ActivityLinkVoteQ);
                                 Yii::app()->jump->error('添加失败!'.'错误信息--('.$ErrorMessage.')');
                                 barek;
                             }
                     }
                     
                      $transaction->commit();
                      Yii::app()->user->setFlash('addform', "添加活动成功！");
                      Yii::app()->jump->success("添加活动成功");
                      $this->refresh();
               }
               
               if($data['Activity']['type_id'] ==101)
               {
                        $data['ActivityLinkSignup']['activity_id'] = $Activity_id;
                        $ActivityLinkSignup->attributes = $data['ActivityLinkSignup'];
  
                        //p_e($ActivityLinkSignup->attributes);
                        if($ActivityLinkSignup->save()){
                             $transaction->commit();
                             Yii::app()->user->setFlash('addform', "添加活动成功！");
                             Yii::app()->jump->success("添加成功");
                             //$this->refresh();
                        }else{
                                 $transaction->rollback();
                                 $ErrorMessage = BootExtend::GetErrorMassage($ActivityLinkSignup);
                                 Yii::app()->jump->error('添加失败!'.'错误信息--('.$ErrorMessage.')');
                                 barek;
                        } 
               }    
               
           }else{ 
                $transaction->rollback();
                $ErrorMessage = BootExtend::GetErrorMassage($Activity);
                Yii::app()->jump->error('登陆失败!'.'错误信息--('.$ErrorMessage.')');
                barek;
           }
           
           
        }
        
            $this->render('add',array(
               'Activity'=>$Activity,
               'ActivityLinkSignup'=>$ActivityLinkSignup,
               'ActivityLinkVoteA'=>$ActivityLinkVoteA,
               'ActivityLinkVoteQ'=>$ActivityLinkVoteQ,
                ));
    }
    
    public function actionAjaxAdd(){
        
        
        $type_id= $_POST['type_id'];
        $title = $_POST['title'];
        

        $sql = "insert into xyh_activity(type_id,title) values('$type_id','$title')";
      
        $result = Yii::app()->db->createCommand($sql)->execute();
        
        
        if ($result){
                echo json_encode(array('success'=>true));
        } else {
                echo json_encode(array('msg'=>'Some errors occured.'));
        }
       
            
    }
       
    function actionEdit($id){
        
        
        //数据源
        $Activity = $this->getPkModelData($id,'Activity');
        
        $Activity->start_time = date('Y-m-d H:i:s',$Activity->start_time);
        $Activity->end_time = date('Y-m-d H:i:s',$Activity->end_time);
        
        
        switch ($Activity->type_id)
        {
            case '101'://报名活动

                $ActivityLinkSignup = $this->getPkModelData($id,'ActivityLinkSignup');
                
//                if($ActivityLinkSignup->signup_start_time){
//
//                    $ActivityLinkSignup->is_need_signup =1;
//                }else{
//                     $ActivityLinkSignup->is_need_signup =2;
//                }
                
                
                
//                if($ActivityLinkSignup->lottery_start_time){
//         
//                    $ActivityLinkSignup->is_need_lottery =1;
//                }else{
//                     $ActivityLinkSignup->is_need_signup =2;
//                }
             

            
                $ActivityLinkVoteQ = new ActivityLinkVoteQ();
                $ActivityLinkVoteQ->unsetAttributes();
                $ActivityLinkVoteA = new ActivityLinkVoteA();
                $ActivityLinkVoteA->unsetAttributes();
//                
                break;
            
            case '102'://投票活动
                $ActivityLinkSignup = new ActivityLinkSignup();
                $ActivityLinkSignup->unsetAttributes();
                $ActivityLinkVoteQ = $this->getModelAllData($id,'ActivityLinkVoteQ');

                $ActivityLinkVoteA = $this->getModelAllData($id,'ActivityLinkVoteA');
                
//                   $ActivityLinkVoteQ = new ActivityLinkVoteQ();
//                $ActivityLinkVoteQ->unsetAttributes();
//                $ActivityLinkVoteA = new ActivityLinkVoteA();
//                $ActivityLinkVoteA->unsetAttributes();
                
                //p($ActivityLinkVoteA);
                break;
            default:
                break;
        }
        
   
        if(isset($_POST['Activity']) && isset($_POST['Activity']))
        {	
      
           $_POST['Activity']['alumni_id'] = isset($_SESSION['alumni_id'])?$_SESSION['alumni_id']:0;
           $_POST['Activity']['start_time'] = strtotime($_POST['Activity']['start_time']);
           $_POST['Activity']['end_time'] = strtotime($_POST['Activity']['end_time']);
           $_POST['Activity']['status'] = 1; 
           
           
           $data =$_POST;
           
           //前端设置了disabled
           unset($data['ActivityLinkSignup']['is_need_checkin']);
           unset($data['ActivityLinkSignup']['is_need_lottery']);
           unset($data['ActivityLinkSignup']['is_need_signup']);
           
           // p_e($data);
           
           $Activity->mtime = time();
           
            if($data['Activity']['is_hot'] ==1){ 
                    $sql_a = "update xyh_activity set is_hot=2 where is_hot=1";
                    $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                  
            }
           
 
           $Activity->attributes = $data['Activity'];
           
          // p_e($Activity->attributes);
           $transaction  =Yii::app()->db->beginTransaction();
           if($Activity->save()){
               
               if($data['Activity']['type_id'] ==102){
                   
                   if(isset($data['ActivityLinkVoteQ']['q_content'])){
                       
                   
                        foreach ($data['ActivityLinkVoteQ']['q_content'] as $k=>$v)
                        {                   
                                 $data['ActivityLinkVoteQ'][$k]['activity_id']= $id;
                                 $data['ActivityLinkVoteQ'][$k]['q_content'] =$v;
                                 $data['ActivityLinkVoteQ'][$k]['type_id'] = $data['ActivityLinkVoteQ']['type_id'];
                                 $data['ActivityLinkVoteQ'][$k]['sort'] =$k;

                                 $ActivityLinkVoteQEdit[$k] = new ActivityLinkVoteQ();

                                 $ActivityLinkVoteQEdit[$k]->attributes =$data['ActivityLinkVoteQ'][$k];
                                 if ($ActivityLinkVoteQEdit[$k]->save()){

                                     $sortA=1;
                                     $vote_id = Yii::app()->db->getLastInsertID(); 
                                     foreach ($data['ActivityLinkVoteA']['a_content'][$k] as $kk=>$vv)
                                    {                   
                                             $data['ActivityLinkVoteA'][$kk]['activity_id']= $id;
                                             $data['ActivityLinkVoteA'][$kk]['vote_q_id']= $vote_id;
                                             $data['ActivityLinkVoteA'][$kk]['a_content'] =$vv;
                                             $data['ActivityLinkVoteA'][$kk]['sort'] =$sortA++;

                                             $ActivityLinkVoteAEdit[$kk] = new ActivityLinkVoteA();

                                             $ActivityLinkVoteAEdit[$kk]->attributes =$data['ActivityLinkVoteA'][$kk];

                                             if ($ActivityLinkVoteAEdit[$kk]->save()){


                                             }
                                             else{
                                                  var_dump($ActivityLinkVoteAEdit[$kk]->getErrors()) ;exit();
                                                 $transaction->rollback();
                                                 Yii::app()->user->setFlash('addform',"答案修改失败");
                                                 barek;
                                             }
                                     }

                                 }
                                 else{

                                     $transaction->rollback();
                                      var_dump($ActivityLinkVoteQEdit[$k]->getErrors()) ;exit();
                                     Yii::app()->user->setFlash('addform',"问题修改失败");
                                     barek;
                                 }
                         }
                     
                    }
                    $transaction->commit();
                    
                     
                     Yii::app()->jump->success("修改活动成功!",Yii::app()->params['adminUrl']."/activity/index");
                    Yii::app()->user->setFlash('addform', "修改活动成功！");
                    $this->refresh();
               }
               if($data['Activity']['type_id'] ==101)
               {
                        $data['ActivityLinkSignup']['activity_id'] = $id;

                        $ActivityLinkSignup->attributes = $data['ActivityLinkSignup'];
                       // p_e($ActivityLinkSignup->attributes);
                        
                        
                        if($ActivityLinkSignup->save()){
                             $transaction->commit();

                             Yii::app()->user->setFlash('addform', "修改活动成功！");
                             $this->refresh();
                        }else{
                                
                                 $transaction->rollback();
                                 
                                 Yii::app()->user->setFlash('addform',"修改报名活动失败".var_dump($ActivityLinkSignup->getErrors()));
                                 barek;
                        } 
               }
              
             
           }else{
                var_dump($Activity->getErrors());exit();
                $transaction->rollback();
                Yii::app()->user->setFlash('addform',"活动修改失败");
                barek;
           }
           
           
        }
            $this->render('edit',array(
               'Activity'=>$Activity,
               'ActivityLinkSignup'=>$ActivityLinkSignup,
               'ActivityLinkVoteA'=>$ActivityLinkVoteA,
               'ActivityLinkVoteQ'=>$ActivityLinkVoteQ,
                ));
        
    }
    
    /**
     * 根据主键获取数据
     * @param int    $id    主键ID
     * @param string $model    模型名
     * return  obj
     */
    
    private function getPkModelData($id,$model){
        
        $ActivityData = $model::model()->findByPk($id);
        if($ActivityData){
            
            return $ActivityData;
        }
        else{
          
            throw new CHttpException(404,"'.$model.'表无数据");
        }
         
    }
    
    /**
     * 根据字段查询所有搜索数据无则生成新模型
     * @param int    $id    主键ID
     * @param string $model    模型名
     * return  obj
     */
     private function getModelAllData($id,$model){
        
        $modelData = $model::model()->findAllByAttributes(array('activity_id' => $id)); 

        if($modelData){
            
            return $modelData;
        }
        else{
          
            return  new $model();
        }
         
    }
    
    /**
     * 根据主键删除一条数据
     * @param int    $id    主键ID
     * @param string $model    模型名
     * return  obj
     */
     private function getDelModelData($id,$model){
        
        $res = $model::model()->deleteByPk($id); 

        if($res){
            
            return $res;
        }
        else{
          
            throw new CHttpException(404,"'.$model.'删除ID:'.$id.'失败");
        }
         
    }
    
    
 
    
    
   public function actionView($id)
   {
            
        
        $Activity = $this->getPkModelData($id,'Activity');
        $Activity->start_time = date('Y-m-d H:i:s',$Activity->start_time);
        $Activity->end_time = date('Y-m-d H:i:s',$Activity->end_time);
        
        
        switch ($Activity->type_id)
        {
            case '101'://报名活动

                $ActivityLinkSignup = $this->getPkModelData($id,'ActivityLinkSignup');
                $ActivityLinkSignup->signup_start_time = date('Y-m-d H:i:s',$ActivityLinkSignup->signup_start_time);
                $ActivityLinkSignup->signup_end_time = date('Y-m-d H:i:s',$ActivityLinkSignup->signup_end_time);
                $ActivityLinkSignup->checkin_start_time = date('Y-m-d H:i:s',$ActivityLinkSignup->checkin_start_time);
                $ActivityLinkSignup->checkin_end_time = date('Y-m-d H:i:s',$ActivityLinkSignup->checkin_end_time);

               // $ActivityLinkSignup->is_need_lottery =1;
               // $ActivityLinkSignup->is_need_signup =1;
            
                $ActivityLinkVoteQ = new ActivityLinkVoteQ();
                $ActivityLinkVoteQ->unsetAttributes();
                $ActivityLinkVoteA = new ActivityLinkVoteA();
                $ActivityLinkVoteA->unsetAttributes();
//                
                break;
            
            case '102'://投票活动
                $ActivityLinkSignup = new ActivityLinkSignup();
                $ActivityLinkSignup->unsetAttributes();
                $ActivityLinkVoteQ = $this->getModelAllData($id,'ActivityLinkVoteQ');
                $ActivityLinkVoteA = $this->getModelAllData($id,'ActivityLinkVoteA');

                break;
            default:
                break;
        }
            
            
             $this->render('view',array(
               'Activity'=>$Activity,
               'ActivityLinkSignup'=>$ActivityLinkSignup,
               'ActivityLinkVoteQ'=>$ActivityLinkVoteQ,
             ));
   
             
            
    }
        
        
        public function Data_Pro($post)
    {   
        //相同数据
       // $post['Activity']['alumni_id'] = isset($_SESSION['alumni_id'])?$_SESSION['alumni_id']:0;
        //$post['Activity']['cat_id'] = 1001;
        
       
        $post['Activity']['start_time'] = strtotime($post['Activity']['start_time']);
        $post['Activity']['end_time'] = strtotime($post['Activity']['end_time']);
        $post['Activity']['status'] = 1; 
        
        
        
        if($post['Activity']['type_id'] ==101){//报名活动
            
             if(isset($post['ActivityLinkSignup']['is_need_checkin']) && $post['ActivityLinkSignup']['is_need_checkin']==1){
                $post['ActivityLinkSignup']['checkin_start_time'] = strtotime($post['ActivityLinkSignup']['checkin_start_time']);
                $post['ActivityLinkSignup']['checkin_end_time'] = strtotime($post['ActivityLinkSignup']['checkin_end_time']);
             
             }else{
                 $post['ActivityLinkSignup']['checkin_start_time']=0;
                 $post['ActivityLinkSignup']['checkin_end_time']=0;
               
             }
             
             
             
             if(isset($post['ActivityLinkSignup']['is_need_signup'])&& $post['ActivityLinkSignup']['is_need_signup']==1){
                $post['ActivityLinkSignup']['signup_start_time'] = strtotime($post['ActivityLinkSignup']['signup_start_time']);
                $post['ActivityLinkSignup']['signup_end_time'] = strtotime($post['ActivityLinkSignup']['signup_end_time']);
                
             }else{
                $post['ActivityLinkSignup']['signup_start_time']=0;
                $post['ActivityLinkSignup']['signup_end_time']=0; 
                
             }  
        }

    return $post;
      
    }
    
    
     public function actionUploads()
    {
        
         $imgUrl ='http://ti.211xyh.com';
         $imgUrlPath=Yii::app()->basePath.'/../';
         
            if(Yii::app()->request->isAjaxRequest)
        {
            $is_thum =0; //缩略图判断值   
            
            switch ($_POST['img_type']){
                
                    case  'file_upload_ws':
                           $targ_w =750; $targ_h =445; 
                           break;
                    case  'file_upload_ws_min':
                           $targ_w =100; $targ_h =100; 
                           $is_thum=1;
                           break;
                    case  'file_upload_ws_vote':
                           $targ_w =750; $targ_h =445; 
                           break;
                    case  'file_upload_ws_min_vote':
                           $targ_w =100; $targ_h =100; 
                           $is_thum=1;
            }
//             if($_POST['img_type']=='file_upload_ws'){
//                   $targ_w =750; $targ_h =445; 
//             }
//             
//             if($_POST['img_type']=='file_upload_ws_min'){
//                   $targ_w =100; $targ_h =100; 
//                   $is_thum=1;
//             }
          
           //$url_root = explode($_SERVER['HTTP_HOST'],$_POST['input_img_url']);
          // $src =  $_SERVER['DOCUMENT_ROOT'] . $url_root[1];
           
           $url_root = explode($imgUrl,$_POST['input_img_url']); //服务器特用
          $src =  $imgUrlPath . $url_root[1];
            
            
           
           $pathinfos = pathinfo($url_root[1]);
           $src_path = $pathinfos['extension'];
         
           //文件判断
          switch ($src_path)
          {
            case 'jpg':
                    $img_r = imagecreatefromjpeg($src);
                break;
            case 'jpeg':
                    $img_r = imagecreatefromjpeg($src);
                break;
            case 'png':
                    $img_r = imagecreatefrompng($src);
                break;

            default:
                    echo 4;
               exit;
                break;
           }

           $dst_r = ImageCreateTrueColor($targ_w,$targ_h);
           $pwd_ture=imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
           $targ_w,$targ_h,$_POST['w'],$_POST['h']);
           @imagejpeg($dst_r,$src);
           
 
           //判断是否缩略图
           if($is_thum){
                //判断是否修改页
                if(isset($_POST['input_img_id']) && !empty($_POST['input_img_id']) &&$pwd_ture){
                    $sql_a = "update xyh_activity set min_banner_url='{$_POST['input_img_url']}' where id=".$_POST['input_img_id'];
                    $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                } 
               
           }else{
               //判断是否修改页
                if(isset($_POST['input_img_id']) && !empty($_POST['input_img_id']) &&$pwd_ture){
                    $sql_a = "update xyh_activity set banner_url='{$_POST['input_img_url']}' where id=".$_POST['input_img_id'];
                    $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                }
           }
            
           //返回信息
            if($pwd_ture)
                echo $_POST['input_img_url'];
            else
                echo 3;
           
        
        }
        
      
        
    }
    
    
     public function actionDelete($id)
    {
        if(Yii::app()->request->isAjaxRequest){
            if($id){
                $Activity = $this->getPkModelData($id,'Activity');
                $Activity->is_del=1;
                $Activity->status=2;
               // $StoreData->name=$StoreData->name.'-'.date('Y-m-d H:i:s',time());
                if($Activity->save(FALSE))
                {
                    if($Activity->type_id ==102){
                        
                    }
                    echo '删除成功';
                }else{
                   var_dump($StoreData->getErrors());
                }
            }
            
        }
    }
    
    
    public function actionLottery($id){
       $res=array();
        if($id){
            $ActivityLinkLottery = new ActivityLinkLottery();
            $ActivityLinkLottery->unsetAttributes();
            
            
           if(isset($_POST['id'])&&isset($_POST['status'])&&isset($_POST['activity_id'])){
            $transaction  =Yii::app()->db->beginTransaction();
            $nowtime =  time();
                if($_POST['status']){//点击抽奖开始
                    //先判断已开始的活动是否结束
                    
                    $sql = "SELECT lottery_start_time,lottery_end_time FROM xyh_activity_link_lottery WHERE status =1 and activity_id={$_POST['activity_id']}";
                    $dataArr = Yii::app()->db->createCommand($sql)->queryRow();
                    
                    if($dataArr&&!$dataArr['lottery_end_time']){
                         $res['status'] = 0;
                         $res['error'][]='请先结束已开始的抽奖!';
                         $transaction->rollback();  
                         echo FALSE;
                         exit();
                         
                    }else{
                                //关闭开始抽奖活动
                                $sql_a = "update xyh_activity_link_lottery set status=2 where status =1 and activity_id={$_POST['activity_id']} ";
                                $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();

                                //
                                $sql_a = "update xyh_activity_link_lottery set lottery_start_time={$nowtime},status=1 where id=$_POST[id] ";
                                $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();

                               if(!$pwd_ture){
                                     $res['status'] = 0;
                                     $res['error'][]='数据写入错误!';
                                     $transaction->rollback(); 
                                     exit();
                                }else{

                                     $res['status'] = TRUE; 
                                }   
                    } 
                    
                }else{//抽奖结束
                    $num =(int)$_POST['num'];
                   $sql_a = "update xyh_activity_link_lottery set lottery_end_time={$nowtime},status=2 where id=$_POST[id]";
                   $pwd_ture = Yii::app()->db->createCommand($sql_a)->execute();
                    if(!$pwd_ture){
                         $res['status'] = 0;
                         $res['error'][]='数据写入错误!';
                         $transaction->rollback(); 
                        echo FALSE;
                         exit();
                    }else{
                         
                         $res['status'] = TRUE; 
                    }
                    
                   
                    
                    $sql = "SELECT user_id  FROM xyh_activity_lottery as al WHERE activity_id={$_POST['activity_id']} and lottery_id ={$_POST['id']} and status=2";
                    $dataArr = Yii::app()->db->createCommand($sql)->queryAll();
                    $user_id =array();
                    if($dataArr){
                         if(count($dataArr) <= $num){
                            foreach($dataArr as $v){
                                    $user_id[]=$v['user_id'];
                                }
                        }else{
                            if($num == 1){
                                $tmp = array_rand($dataArr,$num);
                                $user_id[] =$dataArr[$tmp]['user_id'];
                            }else{
                               $tmp = array_rand($dataArr,$num);
                              
                                foreach ($tmp as $v){
                                    $user_id[] =$dataArr[$v]['user_id'];
                                }  
                            }
                             
                        }
                        $user_ids = implode(',',$user_id);
                        
                     
                        $sql = "update xyh_activity_lottery set status=1 where lottery_id={$_POST['id']} and activity_id={$_POST['activity_id']} and user_id in($user_ids)";
                        $pwd_ture = Yii::app()->db->createCommand($sql)->execute();
                        
                        if(!$pwd_ture){
                         $res['status'] = 0;
                         $res['error'][]='数据写入错误!';
                         $transaction->rollback(); 
                         echo FALSE;
                         exit();
                        }else{
                             $res['status'] = TRUE; 
                        }   
                        
                    }

                
                }
                
                if($res['status'] ==TRUE){
                    $transaction->commit();
                }
           }
         
           
              
           $this->render('lottery',array('ActivityLinkLottery'=>$ActivityLinkLottery,'activity_id'=>$id,'message'=>$res));

        }else{
             throw new CHttpException(404);
        }
        
    }
    
    public function actionLotteryadd(){ 
       
    
       if(isset($_POST['ActivityLinkLottery']) && $_POST['ActivityLinkLottery']){ 
           

             $ActivityLinkLottery = new ActivityLinkLottery();
              $ActivityLinkLottery->unsetAttributes();
           isset($_POST['ActivityLinkLottery']['lottert_num'])?trim($_POST['ActivityLinkLottery']['lottert_num']):'';
           
           $ActivityLinkLottery->attributes = $_POST['ActivityLinkLottery'];
           $ActivityLinkLottery->lottery_start_time=0;
           $ActivityLinkLottery->lottery_end_time =0;
            $ActivityLinkLottery->status =2;
           // p_e($ActivityLinkLottery->attributes);

           if($ActivityLinkLottery->save()){
               $res['status'] = TRUE;
           }else{
               $res['status'] = FALSE;
               $res['error'] = $ActivityLinkLottery->getErrors();
           }
           echo json_encode($res);
           exit();
        }
        
       
        
    }
    
    
    public function actionLotteryview($id,$activity_id,$end_time){
        
        
        if(Yii::app()->request->isAjaxRequest){
            
            if($end_time !='0'){
                $criteria=new CDbCriteria;
                
                $sql = "SELECT user_id  FROM xyh_activity_lottery as al WHERE activity_id={$activity_id} and lottery_id ={$id} and status=1";
                $dataArr = Yii::app()->db->createCommand($sql)->queryAll();
                $user_id =array();
                
     
                if($dataArr){
                     foreach($dataArr as $v){
                        $user_id[]=$v['user_id'];
                     }
                    $user_ids = implode(',', $user_id);   
                        $criteria->addCondition("id in($user_ids)");
                                 $ActivityLottery = new CActiveDataProvider('user', array(
                            'criteria'=>$criteria,
                    ));  
                }else{
                     echo "<script>alert('暂时还没有人参与抽奖!');history.go(0);</script>";
                     exit();
                }
  
                 $this->renderPartial('lotteryview',array('ActivityLottery'=>$ActivityLottery));       

            }else {
                 echo "<script>
                alert('请先结束抽奖后查看中奖名单');
                history.go(0);
                </script>";
            }
            
               
           
                
            
            
        }
        
  
        
        
        
        
    }
     
    
   
    
}